import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginUser, registerUser, getCurrentUser } from '../apis/auth'
import { UserInfo } from '../apis/auth'


export const useAuthStore = defineStore('auth', () => {
  const user = ref<UserInfo | null>(null)
  const isAuthenticated = ref(false)
  const isLoading = ref(false)
  const error = ref('')

  // Check if user is already authenticated
  async function checkAuth() {
    const token = localStorage.getItem('AccessToken')

    if (token) {
      isLoading.value = true
      try {
        const result = await getCurrentUser()
        if (result.code !== 0) {
          error.value = result.message
          return false
        }
        user.value = result.data
        isAuthenticated.value = true
      } catch (err) {
        localStorage.removeItem('AccessToken')
        console.error('Authentication failed:', err)
      } finally {
        isLoading.value = false
      }
    }
  }

  // Login function
  async function login(email: string, password: string) {
    isLoading.value = true
    error.value = ''

    try {
      const result = await loginUser(email, password)
      if (result.code !== 0) {
        error.value = result.message
        return false
      }
      localStorage.setItem('AccessToken', result.data.token)
      await checkAuth()
      return true
    } catch (err: any) {
      error.value = err.message || 'Login failed. Please try again.'
      return false
    } finally {
      isLoading.value = false
    }
  }

  // Register function
  async function register(userData: any) {
    isLoading.value = true
    error.value = ''

    try {
      const result = await registerUser(userData)
      if (result.code !== 0) {
        error.value = result.message
        return false
      }
      localStorage.setItem('AccessToken', result.data.token)
      await checkAuth()
      return true
    } catch (err: any) {
      error.value = err.message || 'Registration failed. Please try again.'
      return false
    } finally {
      isLoading.value = false
    }
  }

  // Logout function
  function logout() {
    localStorage.removeItem('AccessToken')
    user.value = null
    isAuthenticated.value = false
  }

  return {
    user,
    isAuthenticated,
    isLoading,
    error,
    login,
    register,
    logout,
    checkAuth
  }
})